<template>
  <div class="map-test">
    <div v-if="indexMap">
      <el-form-item
        label="地理地址" prop="address">
        <el-autocomplete popper-class="my-autocomplete" style="width: 99%;" class="inline-input" v-model="addressMap"
                         :fetch-suggestions="watchInput"
                         placeholder="请输入要查找的地理位置名称搜索，获取精确坐标" :trigger-on-focus="focus"
                         @select="handleSelect" :debounce="0" @input="changeInput">
          <template slot-scope="{ item }">
            <div class="select-name">{{ item.name }}</div>
            <span class="select-addr" v-if="item.address">地址:{{ item.address }}</span>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item
        label="地图展示">
        <div :id="id" class="container" style="width: 100%; margin-top: 10px; border: 2px solid #000;"
             :style="{'height': mapheight}">
        </div>
      </el-form-item>
    </div>
    <div v-else :id="id" class="container" style="width: 100%;height: 600px;">
    </div>
  </div>
</template>

<script>
  export default {
    name: 'MapShop',
    props: {
      indexMap: {
        type: Boolean,
        default: false
      },
      getLat: {
        default: 0
      },
      getLng: {
        default: 0
      },
      address: {
        type: String,
        default: ''
      },
      id: {
        default: ''
      },
    },
    data() {
      return {
        mapheight: '200px',
        addressMap: '',
        focus: true,
        longitude:0,//经度
        latitude:0,//纬度
        mapList: [], //用来存搜索到的所有地址
        mapVal: '' //创建的地图，赋值用
      }
    },
    mounted () {
    },
    created() {
    },
    methods: {
      changeInput(e) {
        this.mapList = []
      },
      showPosition(position) {
        this.latitude = this.getLat? this.getLat : '30.33864600881732';
        this.longitude = this.getLng? this.getLng :'112.22565830821229';
        //this.city = position.city;
        this.addressMap = this.address
        this.initMap(this.latitude, this.longitude)
      },
      showErr() {
        console.log("定位失败");
        //this.getMyLocation();//定位失败再请求定位，测试使用
        alert('定位失败')
      },
      getMyLocation() {
        /*var geolocation = new qq.maps.Geolocation('N2EBZ-2NMEJ-CYGFF-FYEZC-5M4GE-ZBB7M', "湖北雷霆");
        setTimeout(()=>{
          this.addressMap = this.address
          geolocation.getLocation(this.showPosition, this.showErr);//或者用getLocation精确度比较高
        },200)*/
        this.showPosition()
      },
      handleSelect(item) {
        if(item.location.lat && item.location.lng) {
          this.initMap(item.location.lat, item.location.lng)
          this.$message({
            message: '选中的当前位置坐标获取成功！',
            type: 'success',
            duration: 2000
          })
          console.log(this.addressMap)
          // 子组件传递修改地址信息
          this.$emit('changeAddress', item.value)
          // 子组件传递获取经纬度信息
          this.$emit('getLocation', item.location)
        }else{
          this.$message.error('无法获取当前位置的地理坐标!')
        }
      },

      watchInput(queryString, cb) {
        if(this.mapList.length>0) {
          cb(this.mapList)
        }else {
          this.$jsonp('https://apis.map.qq.com/ws/place/v1/suggestion', {
            key: 'N2EBZ-2NMEJ-CYGFF-FYEZC-5M4GE-ZBB7M',
            region: "荆州市",
            keyword: queryString,
            output: "jsonp"
          }).then(res => {
            if(res.data && res.data.length > 0) {
              const opt = res.data.map(item=>{
                return{
                  value: item.title + "-" + item.address,
                  name: item.title,
                  address: item.address,
                  location: item.location
                }
              })
              this.mapList = opt
              // 调用 callback 返回建议列表的数据
              cb(this.mapList);
            }else{
              cb([{name:'暂无数据'}])
            }
          }).catch(err => {
            console.log(err)
          })
        }
      },
      //初始化地图
      initMap(lat, lng) {
        var that = this
        //如果地图存在，就销毁，下面会重新创建一个
        if (this.mapVal) {
          this.mapVal.destroy()
        }
        //定义地图中心点坐标
        //this.$nextTick是等Dom加载完再执行
        this.$nextTick(() => {
          var center = new TMap.LatLng(lat, lng)
          //定义map变量，调用 TMap.Map() 构造函数创建地图
          this.mapVal = new TMap.Map(document.getElementById(this.id), {
            center: center, //设置地图中心点坐标
            zoom: 17.2, //设置地图缩放级别
            pitch: 43.5, //设置俯仰角
            rotation: 45, //设置地图旋转角度
            viewMode: '2D',
            mapStyleId: "style1" //个性化样式
          });
          //初始化marker
          var marker = new TMap.MultiMarker({
            id: "marker-layer", //图层id
            map: this.mapVal,
            styles: { //点标注的相关样式
              "marker": new TMap.MarkerStyle({
                "width": 25,
                "height": 35,
                "anchor": {
                  x: 16,
                  y: 32
                },
                "src": "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png"
              })
            },
            geometries: [{ //点标注数据数组
              "id": "demo",
              "styleId": "marker",
              "position": new TMap.LatLng(lat, lng),
              "properties": {
                "title": "marker"
              }
            }]
          });

          this.mapVal.on("click", function (evt){
            // 点击地图标注清空子组件输入框绑定值
            that.addressMap = ''
            // 点击地图标注清空父组件输入框绑定值
            that.$emit('changeAddress', '')
            // 点击地图标注清空查询地址列表
            that.mapList = []
            //console.log(evt, '标点坐标')
            marker.updateGeometries([
              {
                "styleId":"marker",
                "id": "demo",
                "position": new TMap.LatLng(evt.latLng.lat, evt.latLng.lng),
              }
            ])
            // 子组件传递获取经纬度信息
            that.$emit('getLocation', evt.latLng)
            // 获取标注点周围地址信息列表
            that.getMapList(evt.latLng)
          })

        })
      },
      //获取周边信息
      getMapList(location) {
        this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/?', {
          location: location.lat + ',' + location.lng,
          key: 'N2EBZ-2NMEJ-CYGFF-FYEZC-5M4GE-ZBB7M',
          get_poi: 1,
          output: "jsonp"
        }).then(res => {
          const optList = res.result.pois.map(item=>{
            return{
              value: item.title + "-" + item.address,
              name: item.title,
              address: item.address,
              location: item.location
            }
          })
          this.mapList = optList
          //console.log(this.mapList)
          //this.address = opt[0].value
        }).catch(err=>{
          console.log(err)
        })
      }
    },
    computed: {},
    filters: {}
  }
</script>

<style lang="scss">
  .my-autocomplete{
    li{
      line-height: normal;
      padding: 7px;
    }
    .select-addr {
      font-size: 12px;
      color: #b4b4b4;
    }
  }

</style>
